#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpSocket>
#include "streammanager.h"
#include "decode.h"
#include <QImage>
#include <QPixmap>
#include <iostream>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
                                          ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = new QTcpSocket();
    socket->connectToHost("localhost", 8888);
    connect(socket, SIGNAL(connected()), this, SLOT(print()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(read()));
}

void MainWindow::print()
{
    std::cerr << "connected!";
}

void MainWindow::read()
{
    QByteArray array;
    BlockReader(socket).stream() >> array;

    fprintf(stderr, "array.size = %d\n", array.size());

    uchar *result = new uchar[1920 * 1080 * 4];
    int out_size;

    int width, height;
    int err = decoder.loop((uint8_t *)array.data(), array.size(), result, &out_size, &width, &height);

    if (err == 0){
        fprintf(stderr, "out_size = %d\n", out_size);
        fprintf(stderr, "width = %d height = %d\n", width, height);
        fprintf(stderr, "err = %d\n", err);
        QImage image = QImage(result, width, height, QImage::Format_RGB888);
        this->setMaximumWidth(width);
        this->setMaximumHeight(height);
        this->setMinimumWidth(width);
        this->setMinimumHeight(height);
        ui->label->setGeometry(0, 0, width, height);
        ui->label->setPixmap(QPixmap::fromImage(image));
    }

    delete []result;
}

MainWindow::~MainWindow()
{
    delete ui;
}
